﻿using LiteFramework.Contract;
using LiteFramework.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;

namespace Website.Action
{
    /// <summary>
    /// Role 的摘要说明
    /// </summary>
    public class Role : BaseHttpHandler_ACE
    {
        protected override ActionResult doAction(HttpContext context, string action)
        {
            switch (action)
            {
                case "list":
                    {
                        #region
                        /// context.Request.QueryString：
                        ///     action=list
                        ///     &_search=false
                        ///     &nd=1498988778443
                        ///     &rows=10
                        ///     &page=1
                        ///     &sidx=timecreated
                        ///     &sord=asc
                        ///     &filters={"groupOp":"AND","rules":[{"field":"name","op":"true","data":"17"},{"field":"description","op":"true","data":"9"}]}

                        int onceTotal = 0;
                        int pageSize = 20;
                        int pageNum = 1;
                        string sordField = null;
                        bool sordAsc = false;


                        if (int.TryParse(this.__context.Request.QueryString["rowTotal"], out onceTotal)) // 一次加载的总记录（一次获取大数据量，前端分页）
                            pageSize = onceTotal;
                        else
                            int.TryParse(this.__context.Request.QueryString["rows"], out pageSize); // 一页加载的总记录
                        int.TryParse(this.__context.Request.QueryString["page"], out pageNum);
                        sordField = this.__context.Request.QueryString["sidx"];
                        sordAsc = (string.IsNullOrEmpty(this.__context.Request.QueryString["sord"]) || this.__context.Request.QueryString["sord"] == "asc");

                        BaseFramework.OrderParam orderParam = null;
                        if (!string.IsNullOrEmpty(sordField))
                        {
                            orderParam = new BaseFramework.OrderParam();
                            foreach (var item in (sordField + (sordAsc?" acs":" desc")).Split(','))
                            {
                                var arr = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                bool isDesc = arr.Length > 1 && arr[1].ToLower() == "desc";
                                orderParam.Add(arr[0], isDesc ? ListSortDirection.Descending : ListSortDirection.Ascending);
                            }
                        }

                        var comp = ServerApplication.ComponentFactory.Create<IRoleContract>();
                        //var datas = comp.GetAll();
                        BaseFramework.PageParam pageArgs = new BaseFramework.PageParam
                        {
                            PageNum = pageNum,
                            PageSize = pageSize,
                            OrderParam = orderParam
                        };
                        var datas = comp.GetList(ref pageArgs);

                        return new ActionResult_AceList<AceModel_Role>(AceModel_Role.ParseList(datas))
                        {
                            TotalRecords = pageArgs.TotalRecords,
                            PageSize = pageSize,
                            PageNum = pageNum,
                            SordAsc = sordAsc,
                        };
                        #endregion
                    }
                case "add":
                    {
                        #region
                        var comp = ServerApplication.ComponentFactory.Create<IRoleContract>();

                        var role = new LiteFramework.Model.Role
                        {
                            Name = this.__context.Request.Form["name"],
                            Description = this.__context.Request.Form["description"],
                        };
                        string err = null;
                        if (!comp.Create(role, out err))
                            return ActionResult.Error(err);
                        else
                            return ActionResult.OK;
                        #endregion
                    }
                case "edit":
                case "mod":
                    {
                        #region
                        var comp = ServerApplication.ComponentFactory.Create<IRoleContract>();
                        var id = this.__context.Request.Form["id"];
                        var role = comp.Get(id);
                        if (role == null) return ActionResult.Error("角色不存在");
                        role.Name = this.__context.Request.Form["name"];
                        role.Description = this.__context.Request.Form["description"];
                        string err = null;
                        if (!comp.Update(role, out err))
                            return ActionResult.Error(err);
                        else
                            return ActionResult.OK;
                        #endregion
                    }
                case "del":
                case "delete":
                    {
                        #region
                        var comp = ServerApplication.ComponentFactory.Create<IRoleContract>();
                        var id = this.__context.Request.Form["id"];
                        if (string.IsNullOrEmpty(id))
                            return ActionResult.Error(ActionStatus.unaccept, "未指定要删除的角色");

                        string err = null;
                        var ids = id.Trim().Split(',');
                        if (ids.Length == 1)
                        {
                            if (!comp.DeleteByPrimaryKey(ids[0], out err))
                                return ActionResult.Error(err);
                            else
                                return ActionResult.OK;
                        }
                        else
                        {
                            var result = comp.DeleteByPrimaryKeys(ids, out err);
                            if (result == 0)
                                return ActionResult.Error(err);
                            else
                                return ActionResult.Succ(result != ids.Length ? string.Format("已删除{0}条记录，共{1}条。", result, ids.Length) : string.Format("已删除{0}条记录。", result));
                        }
                        #endregion
                    }
                case "gettasks":
                    {
                        #region

                        var id = this.__context.Request.QueryString["roleid"];
                        var comp = ServerApplication.ComponentFactory.Create<IRoleContract>();
                        var datas = comp.GetRoleTasks(id);
                        return new ActionResult_AceList<AceModel_Task>(AceModel_Task.ParseList(datas));
                        #endregion
                    }
            }

            return ActionResult.NotSupported;
        }
    }
}